﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using FSViet.Survey.Helpers;

using log4net;

namespace FSViet.Survey
{
	public partial class _Default : System.Web.UI.Page
	{
		ILog _logger = LogManager.GetLogger("RollingFile");
		protected void Page_Load(object sender, EventArgs e)
		{
			string campaignId = string.Empty;
			if (Request.UrlReferrer!=null)
				campaignId = Request.UrlReferrer.Query;

			if (campaignId.Length > 0)
			{
				campaignId = campaignId.Replace("?", "");
				string[] temp = campaignId.ToUpper().Split('&');
				campaignId="";
				for (int i = 0; i < temp.Length; i++)
				{
					if (temp[i].StartsWith("ID="))
						campaignId = temp[i].Replace("ID=", "");
				}
			}
			else if (Request.QueryString["Id"] != null)
				campaignId = Request.QueryString["Id"];
			else
				campaignId = "";
			
			if (campaignId.Length>0)
			{
				Guid id=Guid.Empty;
				try 
				{
					//check site
					string requestUrl = Request.Url.Host;
					string refUrl = Request.UrlReferrer.Host;
					//save log
					_logger.InfoFormat("Default page: Request URL: {0}; RefUrl: {1}", Request.Url, Request.UrlReferrer);
					id = GlobalApplication.GetGuid(campaignId);

					DataHelper dataH = new DataHelper();
					var conn = dataH.CreateConnection();
					conn.Open();
					try
					{
						var site = dataH.Load(conn,"SELECT * FROM Sites WHERE Url LIKE '%,"+requestUrl+",%' AND RefUrl LIKE '%,"+refUrl+",%'", 0, 1);

						if (site.Rows.Count < 1)
							throw new Exception("Invalid request. Not found site");

						var campaign = dataH.Load("SELECT * FROM Campaigns WHERE Id=@Id AND SiteId=@SiteId", 0, 1, 
							dataH.CreateParam("Id", SqlDbType.Char, GlobalApplication.GetGuidS(id)),
							dataH.CreateParam("SiteId", SqlDbType.Char, site.Rows[0]["Id"].ToString())
							);

						string key = GlobalApplication.GetGuidS(Guid.NewGuid());
						string sign = GlobalApplication.GetGuidS(Guid.NewGuid());
						string navigateUrl = "Error.aspx";
						int maxTimeSurvey = 20;
						if (campaign.Rows.Count < 1)
						{
							navigateUrl = string.Format("Campaigns.aspx?SiteId={0}&Hash={1}&Sign={2}",
								site.Rows[0]["Id"].ToString(),
								Security.EncryptPassword(campaign.Rows[0]["SiteId"] + "-" + key),
								sign);
							//throw new Exception("Invalid request. Not found survey");
						}
						else
						{
							if (campaign.Rows[0]["Status"].ToString() != "1")
								throw new Exception("Campaign is not running.");

							//Session["CampaignId"] = campaign.Rows[0]["Id"].ToString();
							//Session["SiteId"] = campaign.Rows[0]["SiteId"].ToString();
							
							navigateUrl=
								string.Format("VKHTCNNSurvey.aspx?SiteId={0}&CampaignId={1}&Hash={2}&Sign={3}&TotalQuestionOnPage={4}",
								campaign.Rows[0]["SiteId"],
								campaign.Rows[0]["Id"],
								Security.EncryptPassword(campaign.Rows[0]["SiteId"] + "-" + campaign.Rows[0]["Id"] + "-" + key),
								sign,
								campaign.Rows[0]["TotalQuestionOnPage"]);

							maxTimeSurvey = (int)campaign.Rows[0]["MaxTimeSurvey"];
						}

						HttpRuntime.Cache.Insert(sign, key,
								null, DateTime.Now.AddMinutes(maxTimeSurvey),
								System.Web.Caching.Cache.NoSlidingExpiration);

						Page.RegisterClientScriptBlock("StartSurvey","<script>document.location.href='"+navigateUrl+"'</script>");
					}
					finally
					{
						conn.Close();
					}
				}
				catch (Exception ex)
				{
					Response.Redirect("~/Error.aspx?msg=" + Server.UrlEncode(ex.Message));
				}
			}
			else
				Response.Redirect("~/Campaigns.aspx");
		}
	}
}
